<template>
	<!--	class="h-full"-->
	<a-card :bordered="false" class="mb-3">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<div class="flex justify-between items-center">
				<a-space :size="16">
					<a-input-group compact>
						<a-select v-model:value="searchFormState.searchType" @change="onSearchType">
							<!--							<a-select-option :value="0">订单编号</a-select-option>-->
							<a-select-option :value="1">甲方抬头</a-select-option>
							<!--							<a-select-option :value="2">合同编号</a-select-option>-->
						</a-select>
						<a-input
							v-model:value="searchTextComputed"
							style="width: 200px"
							placeholder="请输入关键词搜索"
							allowClear
							@pressEnter="table.clearRefreshSelected(true)"
						/>
					</a-input-group>
					<a-input-group compact>
						<a-select
							placeholder="请选择"
							v-model:value="searchFormState.userType"
							class="w-[100px]"
							:options="[
								{ label: '创建人', value: 0 },
								{ label: '签约人', value: 1 }
							]"
							:filter-option="false"
							@change="onUserTypeChange"
						/>
						<a-select
							v-model:value="searchFormState.userVal"
							placeholder="请选择"
							class="w-[200px]"
							:options="createUserOptions"
							:filter-option="createUserFilterOption"
							allowClear
							showSearch
						/>
					</a-input-group>

					<a-button type="primary" @click="onSearchSubmit">查询</a-button>
					<a-button @click="filterVisible = true">更多筛选</a-button>
				</a-space>
				<a-space> </a-space>
			</div>
		</a-form>
	</a-card>

	<a-card :bordered="false">
		<!-- :row-selection="options.rowSelection" -->
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 1200 }"
		>
			<!--			<template #operator class="table-operator">-->
			<!--				<a-space>-->
			<!--					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('customerOrderAdd')">-->
			<!--						<template #icon><plus-outlined /></template>-->
			<!--						新增-->
			<!--					</a-button>-->
			<!--					<xn-batch-delete-->
			<!--						v-if="hasPerm('customerOrderBatchDelete')"-->
			<!--						:selectedRowKeys="selectedRowKeys"-->
			<!--						@batchDelete="deleteBatchCustomerOrder"-->
			<!--					/>-->
			<!--				</a-space>-->
			<!--			</template>-->
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'orderNo'">
					<a v-if="hasPerm('bizOrderView')" @click="onDetail(record.id)">{{ record.orderNo }}</a>
					<span v-else>{{ record.orderNo }}</span>
				</template>
				<template v-if="column.dataIndex === 'orderStatus'">
					{{ $TOOL.dictTypeData('ORDER_STATUS', record.orderStatus) }}
				</template>
				<template v-if="column.dataIndex === 'signPayment'">
					{{ $TOOL.dictTypeData('SignPayment', record.signPayment) }}
				</template>
				<template v-if="column.dataIndex === 'businessType'">
					{{ $TOOL.dictTypeData('BUSINESS_TYPE', record.businessType) }}
				</template>
				<template v-if="column.dataIndex === 'paymentMethod'">
					{{ $TOOL.dictTypeData('PAYMENT_METHOD', record.paymentMethod) }}
				</template>
				<template v-if="column.dataIndex === 'depositAmount'">
					{{ record.paymentMethod === 'FULL' ? '-' : record.depositAmount ?? '-' }}
				</template>
				<template v-if="column.dataIndex === 'balancePayment'">
					{{ record.paymentMethod === 'FULL' ? '-' : record.balancePayment ?? '-' }}
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a v-if="hasPerm('bizOrderView')" @click="onDetail(record.id)">查看详情</a>
						<!--						<a @click="formRef.onOpen(record)" v-if="hasPerm('customerOrderEdit')">编辑</a>-->
						<!--						<a-divider type="vertical" v-if="hasPerm(['customerOrderEdit', 'customerOrderDelete'], 'and')" />-->
						<!--						<a-popconfirm title="确定要删除吗？" @confirm="deleteCustomerOrder(record)">-->
						<!--							<a-button type="link" danger size="small" v-if="hasPerm('customerOrderDelete')">删除</a-button>-->
						<!--						</a-popconfirm>-->
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>

	<!-- 更多筛选条件 -->
	<a-modal v-model:visible="filterVisible" title="更多筛选" :footer="null" :width="400" @cancel="onFilterCancel">
		<a-form ref="filterSearchFormRef" :model="searchFormState" :label-col="labelCol">
			<!--			<a-form-item label="订单来源" name="orderFrom">-->
			<!--				<a-select-->
			<!--					v-model:value="searchFormState.orderFrom"-->
			<!--					placeholder="请选择"-->
			<!--					:options="orderSourceOptions"-->
			<!--					style="width: 100%"-->
			<!--					allowClear-->
			<!--				/>-->
			<!--			</a-form-item>-->
			<a-form-item label="订单状态" name="orderStatus">
				<a-select
					v-model:value="searchFormState.orderStatus"
					placeholder="请选择"
					:options="orderStatusOptions"
					style="width: 100%"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="订单金额" name="orderAmount">
				<a-input-group compact>
					<a-select v-model:value="searchFormState.orderAmountType">
						<a-select-option :value="0">=</a-select-option>
						<a-select-option :value="1">&gt;</a-select-option>
						<a-select-option :value="2">&lt;</a-select-option>
					</a-select>
					<a-form-item-rest>
						<a-input
							v-model:value="searchFormState.orderAmount"
							style="width: calc(100% - 52px)"
							placeholder="请输入"
							allowClear
						/>
					</a-form-item-rest>
				</a-input-group>
			</a-form-item>
			<a-form-item label="付款日期" name="paymentDate">
				<a-range-picker v-model:value="searchFormState.paymentDate" valueFormat="YYYY-MM-DD" show-date allowClear />
			</a-form-item>
			<!--			<a-form-item label="签约场景" name="signPayment">-->
			<!--				<a-select-->
			<!--					v-model:value="searchFormState.signPayment"-->
			<!--					placeholder="请选择"-->
			<!--					:options="signPaymentOptions"-->
			<!--					allowClear-->
			<!--				/>-->
			<!--			</a-form-item>-->
			<a-form-item label="付款类型" name="paymentMethod">
				<a-select
					v-model:value="searchFormState.paymentMethod"
					placeholder="请选择"
					:options="payMethodOptions"
					allowClear
					@change="onBusinessTypeChange"
				/>
			</a-form-item>
			<!--			<a-form-item label="合同模板" name="contractTemplate">-->
			<!--				<a-select-->
			<!--					v-model:value="searchFormState.contractTemplate"-->
			<!--					placeholder="请选择"-->
			<!--					:options="contractTemplateOptions"-->
			<!--					allowClear-->
			<!--				/>-->
			<!--			</a-form-item>-->
			<a-form-item label="业务类型" name="businessType">
				<a-select
					v-model:value="searchFormState.businessType"
					placeholder="请选择"
					:options="businessTypeOptions"
					allowClear
					@change="onBusinessTypeChange"
				/>
			</a-form-item>
			<a-form-item label="服务类目" name="serviceCategoryId">
				<a-cascader
					v-model:value="searchFormState.serviceCategoryId"
					:options="categorySearchs"
					changeOnSelect
					placeholder="请选择"
				></a-cascader>
			</a-form-item>
			<a-form-item label="乙方抬头">
				<a-select v-model:value="searchFormState.secondPartyId" :options="partyOptions" placeholder="请选择"></a-select>
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" size="small" @click="onFilterReset">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="onFilterSubmit">筛选</a-button>
				<a-button @click="onFilterCancel">取消</a-button>
			</a-space>
		</div>
	</a-modal>
</template>

<script setup name="order">
	import tool from '@/utils/tool'
	import customerOrderApi from '@/api/biz/customerOrderApi'
	import contractApi from '@/api/biz/contractApi'
	import erpApi from '@/api/biz/bizCommonApi'
	import bizContractApi from '@/api/biz/bizContractApi'
	import { signMethodEnum } from '@/views/biz/contractManagement/enum/contractEnum'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'

	const router = useRouter()
	const tableCache = useTableCache('order', ['bizOrder', 'bizOrderDetail'])

	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			Object.assign(searchFormState, tableCacheData)
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}
	})

	const filterVisible = ref(false)
	const labelCol = { style: { width: '80px' } }

	let searchFormState = reactive({
		searchType: 1,
		keyword: null,
		userType: 0,
		orderAmountType: 0
	})
	const searchTextComputed = computed({
		get() {
			return searchFormState.keyword
		},
		set(val) {
			searchFormState.keyword = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const searchFormRef = ref()
	const filterSearchFormRef = ref()
	const table = ref()
	const pageNum = ref(1)
	const pageSize = ref(10)

	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	// 查询区域显示更多控制
	const advanced = ref(false)
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}
	const columns = [
		// {
		// 	title: '订单编号',
		// 	dataIndex: 'orderNo',
		// 	width: 200,
		// 	fixed: true
		// },
		{
			title: '甲方抬头',
			dataIndex: 'firstParty',
			width: 260,
			ellipsis: true
		},
		{
			title: '乙方抬头',
			dataIndex: 'secondPartyName',
			width: 260,
			ellipsis: true
		},
		{
			title: '订单状态',
			dataIndex: 'orderStatus',
			width: 100
		},
		// {
		// 	title: '订单来源',
		// 	dataIndex: 'orderFrom',
		// 	width: 100
		// },
		{
			title: '付款类型',
			dataIndex: 'paymentMethod',
			width: 100,
			ellipsis: true
		},
		{
			title: '业务类型',
			dataIndex: 'businessType',
			width: 100,
			ellipsis: true
		},
		{
			title: '服务类目',
			dataIndex: 'serviceProjectName',
			width: 300,
			ellipsis: true,
			customRender: ({ text, record }) => `${record.serviceClassName} > ${record.serviceTypeName} > ${text}`
		},
		{
			title: '订单金额',
			dataIndex: 'orderAmount',
			width: 100,
			ellipsis: true
		},
		{
			title: '定金金额',
			dataIndex: 'depositAmount',
			width: 100,
			ellipsis: true
		},
		{
			title: '尾款金额',
			dataIndex: 'balancePayment',
			width: 100,
			ellipsis: true
		},
		{
			title: '服务时长',
			dataIndex: 'serviceLife',
			width: 90,
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '赠送时长',
			dataIndex: 'giveMonth',
			width: 90,
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '开始服务月',
			dataIndex: 'serviceStime',
			width: 100,
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '结束服务月',
			dataIndex: 'serviceEtime',
			width: 90,
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '签约人',
			dataIndex: 'secondPartyPerson',
			width: 90,
			align: 'center',
			ellipsis: true
		},
		{
			title: '创建人',
			dataIndex: 'createUserName',
			width: 120
		},
		{
			title: '创建时间',
			dataIndex: 'createAt',
			width: 150
		},
		{
			title: '付款时间',
			dataIndex: 'paymentDate',
			width: 150
		}
		// {
		// 	title: '合同编号',
		// 	dataIndex: 'contractNo',
		// 	width: 200
		// },
		// {
		// 	title: '合同模板',
		// 	dataIndex: 'contractTemplateName',
		// 	width: 180,
		// 	ellipsis: true,
		// 	customRender: ({ text }) => text || '-'
		// },
		// {
		// 	title: '签约方式',
		// 	dataIndex: 'signMethod',
		// 	width: 100,
		// 	align: 'center',
		// 	customRender: ({ text }) => signMethodEnum[text] || '-'
		// },
		// {
		// 	title: '签约场景',
		// 	dataIndex: 'signPayment',
		// 	width: 150,
		// 	ellipsis: true
		// },
	]
	// 操作栏通过权限判断是否显示
	// if (hasPerm(['customerOrderEdit', 'customerOrderDelete'])) {
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: '100px',
		fixed: 'right'
	})
	// }
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		const { searchType, keyword } = searchFormState
		if (keyword) {
			const typeKeyList = ['orderNo', 'firstParty', 'contractNo']
			searchFormState[typeKeyList[searchType]] = keyword
		} else {
			onSearchType()
		}

		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))

		// paymentDate范围查询条件重载
		if (searchFormParam.paymentDate) {
			searchFormParam.startPaymentDate = searchFormParam.paymentDate[0]
			searchFormParam.endPaymentDate = searchFormParam.paymentDate[1]
			delete searchFormParam.paymentDate
		}

		if (searchFormParam.serviceCategoryId) {
			const [serviceClassId = null, serviceTypeId = null, serviceProjectId = null] = searchFormParam.serviceCategoryId
			searchFormParam.serviceCategoryId = searchFormParam.serviceCategoryId.join(',')
			searchFormParam.serviceClassId = serviceClassId
			searchFormParam.serviceTypeId = serviceTypeId
			searchFormParam.serviceProjectId = serviceProjectId
		}

		const { userType, userVal } = searchFormParam
		if (userVal) {
			if (userType === 0) {
				searchFormParam.createUser = userVal
				searchFormParam.secondPartyPerson = null
			} else if (userType === 1) {
				searchFormParam.createUser = null
				searchFormParam.secondPartyPerson = userVal
			}
		} else {
			searchFormParam.createUser = null
			searchFormParam.secondPartyPerson = null
		}
		return customerOrderApi.customerOrderPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		table.value.refresh(true)
	}

	// 详情
	const onDetail = (id) => {
		const { localPagination } = table.value
		tableCache.set({ ...searchFormState, pageNum: localPagination.current, pageSize: localPagination.pageSize })
		router.push('/biz/order/detail?id=' + id)
	}

	// 删除
	const deleteCustomerOrder = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		customerOrderApi.customerOrderDelete(params).then(() => {
			table.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchCustomerOrder = (params) => {
		customerOrderApi.customerOrderDelete(params).then(() => {
			table.value.clearRefreshSelected()
		})
	}
	const orderStatusOptions = tool.dictList('ORDER_STATUS')
	const orderSourceOptions = [
		{ label: 'ERP', value: 'ERP' },
		{ label: 'CRM', value: 'CRM' }
	]
	const contractTemplateOptions = ref([])
	const signPaymentOptions = tool.dictList('SignPayment')
	const payMethodOptions = tool.dictList('PAYMENT_METHOD')
	const businessTypeOptions = tool.dictList('BUSINESS_TYPE')
	const createUserOptions = ref([])
	const createUserFilterOption = (input, option) => {
		return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}

	/**
	 * 获取所有服务类目
	 */
	const categorySearchs = ref([])
	const getCategorys = () => {
		erpApi.getCategory().then((res) => {
			categorySearchs.value = res
		})
	}
	/**
	 * 乙方信息列表获取
	 */
	const partyOptions = ref([])
	const getContractPartbList = () => {
		bizContractApi.getContractPartbList({}).then((res) => {
			partyOptions.value = res.map((item) => {
				return {
					value: item.id,
					label: item.partyName
				}
			})
		})
	}

	onMounted(() => {
		contractOrderCreateUserList()
		contractTemplateList()
		getCategorys()
		getContractPartbList()
	})

	const onUserTypeChange = () => {
		searchFormState.userVal = ''
		contractOrderCreateUserList()
	}

	const contractOrderCreateUserList = () => {
		const requestData = !searchFormState.userType
			? bizContractApi.authUserSelector({})
			: bizContractApi.signUserList({
					type: 2 // 空或0-合同列表 1-历史合同列表 2-订单合同
			  })
		requestData.then((res) => {
			createUserOptions.value = res.map((item) => {
				return !searchFormState.userType
					? {
							label: item.name,
							value: item.id
					  }
					: {
							label: item,
							value: item
					  }
			})
		})
	}

	const contractTemplateList = (data = {}) => {
		contractApi.contractTemplateList(data).then((data) => {
			contractTemplateOptions.value = data.map((item) => ({
				value: item.templateId,
				label: item.templateName
			}))
		})
	}

	const onSearchType = (value) => {
		Object.assign(searchFormState, {
			keyword: null,
			orderNo: null,
			firstParty: null,
			contractNo: null
		})
	}
	const onBusinessTypeChange = (value) => {
		searchFormState.contractTemplate = null
		contractTemplateList({ businessTypeId: value })
	}
	const onSearchSubmit = () => {
		table.value.refresh(true)
	}
	const onFilterReset = () => {
		Object.assign(searchFormState, {
			searchType: 1,
			keyword: null,
			orderNo: null,
			firstParty: null,
			contractNo: null,
			userType: 0,
			userVal: null,
			createUser: null,
			secondPartyPerson: null,
			orderStatus: null,
			orderAmountType: 0,
			orderAmount: null,
			paymentDate: null,
			startPaymentDate: null,
			endPaymentDate: null,
			paymentMethod: null,
			businessType: null,
			serviceCategoryId: null,
			secondPartyId: null,
			serviceClassId: null,
			serviceTypeId: null,
			serviceProjectId: null
		})
		contractTemplateList()
	}
	const onFilterSubmit = () => {
		table.value.refresh(true)
		filterVisible.value = false
	}
	const onFilterCancel = () => {
		filterVisible.value = false
	}
</script>
